package cn.vc.wallet.controller;

import cn.vc.auth.entity.po.VUser;
import cn.vc.wallet.entity.po.TopUp;
import cn.vc.wallet.service.TopUpService;
import cn.vc.wallet.util.SecurityUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 扫码支付的测试
 * @Author: mo
 * @Date: 2024-03-25 21:25
 **/
@Controller
public class PayController {

    // app_id
    @Value("${pay.alipay.APP_ID}")
    String APP_ID;
    // 应用私钥
    @Value("${pay.alipay.APP_PRIVATE_KEY}")
    String APP_PRIVATE_KEY;
    // 支付宝公钥
    @Value("${pay.alipay.ALIPAY_PUBLIC_KEY}")
    String ALIPAY_PUBLIC_KEY;
    // 服务器异步通知页面路径 需http://或者https://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问
    @Value("${payurl.notify_url}")
    private String NOTIFY_URL;
    // 页面跳转同步通知页面路径 需http://或者https://格式的完整路径，不能加?id=123这类自定义参数，必须外网可以正常访问 商户可以自定义同步跳转地址
    @Value("${payurl.return_url}")
    public String RETURN_URL;
    // 请求网关地址
    public static String URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    // 编码
    public static String CHARSET = "UTF-8";
    // 返回格式
    public static String FORMAT = "json";
    // 签名方式RSA2
    public static String SIGN_TYPE = "RSA2";
    public static String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";

    @Autowired
    private TopUpService topUpService;


    @GetMapping("/pay/alipay")
    @ResponseBody
    public String alipay(HttpSession session, Model model,
                         @RequestParam("dona_money") double dona_money,
                         @RequestParam("dona_id") int dona_id,
                         @RequestParam("return_url") String return_url) throws AlipayApiException {
        VUser vUser = SecurityUtil.getUser();
        if (vUser==null) return null;

        //把dona_id项目id 放在session中
        session.setAttribute("dona_id", dona_id);

        //生成订单号（支付宝的要求？）
        String time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
//        String user = UUID.randomUUID().toString().replace("-","").toUpperCase();

//        String OrderNum = time+user;
        String OrderNum = vUser.getId()+time;
        // 插入数据库
        TopUp topUp = new TopUp();
        topUp.setId(OrderNum);
        topUp.setUserId(vUser.getId());
        long amount = Math.round(dona_money);
        topUp.setAmount(amount);
        topUp.setDiamond(amount*10);
        topUp.setPay_or_not(false);
        topUpService.add(topUp);

        //调用封装好的方法（给支付宝接口发送请求）
        return sendRequestToAlipay(OrderNum, dona_money,"ghjk", RETURN_URL);
    }

    /**
     * 支付宝官方提供的接口
     * @param outTradeNo 订单号
     * @param totalAmount 订单金额
     * @param subject 订单名称
     * @return
     * @throws AlipayApiException
     */
    private String sendRequestToAlipay(String outTradeNo,Double totalAmount,String subject, String return_url) throws AlipayApiException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL,APP_ID,APP_PRIVATE_KEY,FORMAT,CHARSET,ALIPAY_PUBLIC_KEY,SIGN_TYPE);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
//        alipayRequest.setReturnUrl(RETURN_URL);
        alipayRequest.setReturnUrl(return_url);
        alipayRequest.setNotifyUrl(NOTIFY_URL);

        //商品描述（可空）
        String body="";
        alipayRequest.setBizContent("{\"out_trade_no\":\"" + outTradeNo + "\","
                + "\"total_amount\":\"" + totalAmount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //请求
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        return result;
    }


    /**
     * 支付完成后的异步调用（需要公网IP）
     * @param request
     * @param response
     * @throws IOException
     * @throws AlipayApiException
     */
    @PostMapping("/paynotify")
    public void paynotify(HttpServletRequest request, HttpServletResponse response) throws IOException, AlipayApiException {
        System.out.println(request);
    }


    /**
     * 支付完成后的同步调用（无需公网IP）
     * @param request
     * @param session
     * @param model
     * @return
     * @throws AlipayApiException
     * @throws UnsupportedEncodingException
     * @throws UnsupportedEncodingException
     */
    @RequestMapping("/pay/return")
    public String returnUrlMethod(HttpServletRequest request, HttpSession session, Model model) throws AlipayApiException, UnsupportedEncodingException, UnsupportedEncodingException {
        System.out.println("=================================同步回调=====================================");

        // 获取支付宝GET过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        System.out.println(params);//查看参数都有哪些
        //验证签名（支付宝公钥）
        boolean signVerified = AlipaySignature.rsaCheckV1(params, ALIPAY_PUBLIC_KEY, CHARSET, SIGN_TYPE); // 调用SDK验证签名
        //验证签名通过
        if(signVerified){
            // 商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
            // 支付宝交易流水号
            String alipay_trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
            // 付款金额
            float money = Float.parseFloat(new String(request.getParameter("total_amount").getBytes("ISO-8859-1"), "UTF-8"));

            System.out.println("商户订单号="+out_trade_no);
            System.out.println("支付宝交易号="+alipay_trade_no);
            System.out.println("付款金额="+money);

            //在这里编写自己的业务代码（对数据库的操作）
			/**/
            topUpService.paymentCompletion(out_trade_no, alipay_trade_no);
			/**/
            //跳转到提示页面（成功或者失败的提示页面）
            model.addAttribute("flag",1);
            model.addAttribute("msg","支持");
            model.addAttribute("out_trade_no", out_trade_no);
            model.addAttribute("money", money);

            return "index";
        }else{
            //跳转到提示页面（成功或者失败的提示页面）
            model.addAttribute("flag",0);
            model.addAttribute("msg","支持");

            return "index";
        }
    }


}
